//
//  WeekCSVParser.m
//  RegBars
//
//  Created by Huu Nhat on 9/25/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "WeekCSVParser.h"

@implementation WeekCSVParser
@synthesize delegate;
@synthesize currentWeek;
@synthesize urlString;

- (void) getWeekFromUrl:(NSString*) url withDelegate:(id)theDelegate storeInArray:(NSMutableArray*) array {
    NSLog(@"url = %@",url);
    self.urlString = [[NSString alloc] initWithFormat:@"%@", url];
	self.delegate = theDelegate;
	NSString *contentCSV = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSASCIIStringEncoding error:nil];
	if (contentCSV != NULL) {
		NSMutableArray *textLines = [[NSMutableArray alloc] init];
		[textLines setArray:[contentCSV componentsSeparatedByString:@"\n"]];
		if ([textLines count] > 1) {
			[textLines removeObjectAtIndex:0];
			for (NSString *line in textLines) {
				NSMutableArray *lineContentsArray = [[NSMutableArray alloc] initWithArray:[line componentsSeparatedByString:@";"]];
				if ([lineContentsArray count] == 8) {
					if (currentWeek) {
						currentWeek = nil;
					}
					currentWeek = [[Week alloc] init];
					currentWeek.date = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:0]];
					currentWeek.day = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:1]];
					currentWeek.goodGroup  = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:2]];
					currentWeek.name = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:3]];
					currentWeek.price = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:4]];
					currentWeek.student = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:5]];
					currentWeek.beg = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:6]];
					currentWeek.gast = [NSString stringWithFormat:@"%@",[lineContentsArray objectAtIndex:7]];
					if (![currentWeek.name isEqualToString:@""]) {
						[array addObject:currentWeek];
					}
					[currentWeek release];
				}
				[lineContentsArray release];
			}
		}
	}
	if ([array count]!=0) {
		[self.delegate didEndParseCSVFile:array withUrl:self.urlString];
	}
}

- (void) dealloc{
    [urlString release];
	[super dealloc];
}

@end
